package com.bolinfest.closure;

import java.io.File;
import java.io.IOException;

import org.kohsuke.args4j.CmdLineException;

import com.google.common.base.Charsets;
import com.google.common.collect.HashMultimap;
import com.google.common.io.Files;
import com.google.javascript.jscomp.CommandLineRunner;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.CustomPassExecutionTime;

public class ExportPublicMembersCompilerRunner extends CommandLineRunner {

  private ExportPublicMembersPass exportPublicMembersPass;
  
  public ExportPublicMembersCompilerRunner(String[] args) throws
      CmdLineException {
    super(args);
  }

  @Override
  public CompilerOptions createOptions() {
    CompilerOptions options = super.createOptions();
    if (options.customPasses == null) {
      options.customPasses = HashMultimap.create();
    }
    exportPublicMembersPass = new ExportPublicMembersPass(getCompiler());
    options.customPasses.put(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS,
        exportPublicMembersPass);

    // Try to reduce code size by stripping debug information.
    DebugStrippingCompilerRunner.applyDebugStrippingOptions(options);

    return options;
  }

  @Override
  public int doRun() throws FlagUsageException, IOException {
    int result = super.doRun();
    if (result == 0) {
      String exportsJs = exportPublicMembersPass.getExportsJs();
      Files.write(exportsJs, new File("build/closure-lite-exports.js"),
          Charsets.UTF_8);
      String externsJs = exportPublicMembersPass.getExternsJs();
      Files.write(externsJs, new File("build/closure-lite-externs.js"),
          Charsets.UTF_8);
    }
    return result;
  }

  public static void main(String[] args) { 
    try {
      new ExportPublicMembersCompilerRunner(args).run();
    } catch (CmdLineException e) {
      System.exit(-1);
    }
  }
}
